<template>
  <div v-if="props.showValue" class="c-property-certificate-input-wrapper">
    <div v-if="!isTemplateSelected" class="input-container">
      <el-select
        v-model="selectedFormat"
        placeholder="选择产权证格式"
        style="width: 100%"
        @change="handleFormatChange"
        :disabled="props.disabled || props.loading"
      >
        <el-option
          v-for="format in props.formatOptions"
          :key="format.value"
          :label="format.label"
          :value="format.value"
        />
      </el-select>
    </div>
    <div v-else class="input-container">
      <div class="input-wrapper">
        <span v-for="(part, index) in formatParts" :key="index" class="format-part">
          {{ part.type === 'text' ? part.value : '' }}
          <input
            v-if="part.type === 'input'"
            v-model="inputValues[getInputIndex(index)]"
            type="text"
            :maxlength="part.length"
            :placeholder="`${part.length}位`"
            :disabled="props.disabled || props.loading"
            @input="handleInput(index)"
            :style="{ width: `${Math.max(part.length * 12, 40)}px` }"
            class="part-input"
          />
        </span>
        <el-icon
          v-if="!props.disabled && !props.loading"
          class="clear-icon"
          @click="handleClear"
          title="清除并重新选择格式"
        >
          <CircleClose />
        </el-icon>
      </div>
    </div>
    <div v-if="showRequiredMark && !props.hideRequiredMark" class="required-mark">*</div>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { PropType } from 'vue'
import { ElSelect, ElOption } from 'element-plus'
import { ElIcon } from 'element-plus'
import { CircleClose } from '@element-plus/icons-vue'

// 定义模板部分的类型接口
interface FormatTextPart {
  type: 'text'
  value: string
}

interface FormatInputPart {
  type: 'input'
  length: number
}

type FormatPart = FormatTextPart | FormatInputPart

interface FormatOption {
  value: string
  label: string
  template: FormatPart[]
}

/**
 * 产权证输入框组件，增强了以下功能：
 * 1. 下拉选择产权证格式
 * 2. 自动显示需要输入的字符个数模板
 * 3. 输入完成自动跳转到下一个输入位置
 * 4. 加载状态管理
 * 5. 可配置的required标记
 */
const props = defineProps({
  // 绑定值
  modelValue: {
    type: String,
    default: '',
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  // 是否显示加载状态
  loading: {
    type: Boolean,
    default: false,
  },
  // 是否显示必填标记
  showRequiredMark: {
    type: Boolean,
    default: false,
  },
  // 是否隐藏必填标记（优先级高于showRequiredMark）
  hideRequiredMark: {
    type: Boolean,
    default: false,
  },
  // 是否显示
  showValue: {
    type: Boolean,
    default: true,
  },
  // 是否显示上手值
  showOldValue: {
    type: Boolean,
    default: false,
  },
  // 上手值
  oldValue: {
    type: String,
    default: '',
  },
  // 产权证格式选项列表（从外部传入）
  formatOptions: {
    type: Array as PropType<FormatOption[]>,
    default: () => [],
  },
})

const emit = defineEmits(['update:modelValue', 'change', 'focus', 'blur'])
  
  // 当前选择的格式 - 初始为空字符串，不默认选择第一个
const selectedFormat = ref('')
// 格式模板解析后的部分 - 初始为空数组
const formatParts = ref<FormatPart[]>([])
// 各输入部分的值
const inputValues = ref<(string | null)[]>([])
// 内部加载状态
const isLoading = ref(props.loading)
// 是否已选择模板
const isTemplateSelected = ref(false)

// 是否显示必填标记
const showRequiredMark = computed(() => {
  return props.showRequiredMark && !props.hideRequiredMark
})

// 初始化输入值数组
const initInputValues = () => {
  const count = formatParts.value.filter((part) => part.type === 'input').length
  inputValues.value = Array(count).fill('')
}

// 监听格式变化
const handleFormatChange = () => {
  const format = props.formatOptions.find((option) => option.value === selectedFormat.value)
  if (format) {
    formatParts.value = format.template
    initInputValues()
    updateModelValue()
    // 设置已选择模板标志
    isTemplateSelected.value = true
    
    // 选择模板后，第一个输入框自动聚焦
    setTimeout(() => {
      const firstInput = document.querySelector('.part-input')
      if (firstInput) {
        (firstInput as HTMLInputElement).focus()
      }
    }, 100)
  }
}

// 清除并重置为选择状态
const handleClear = () => {
  initInputValues()
  updateModelValue()
  isTemplateSelected.value = false
  selectedFormat.value = ''
}

// 解析值到各个输入部分
const parseValueToInputs = (value: string) => {
  let remainingValue = value
  let inputIndex = 0

  for (const part of formatParts.value) {
    if (part.type === 'text') {
      // 尝试匹配文本部分
      const matchIndex = remainingValue.indexOf(part.value)
      if (matchIndex === 0) {
        remainingValue = remainingValue.slice(part.value.length)
      }
    } else if (part.type === 'input' && inputIndex < inputValues.value.length) {
      // 提取输入部分的值
      inputValues.value[inputIndex] = remainingValue.slice(0, part.length)
      remainingValue = remainingValue.slice(part.length)
      inputIndex++
    }
  }
}

// 更新绑定值
const updateModelValue = () => {
  let result = ''
  let inputIndex = 0

  for (const part of formatParts.value) {
    if (part.type === 'text') {
      result += part.value
    } else if (part.type === 'input') {
      result += inputValues.value[inputIndex] || ''
      inputIndex++
    }
  }

  emit('update:modelValue', result)
  emit('change', result)
}

// 计算formatParts索引对应的inputValues索引
const getInputIndex = (formatPartsIndex: number) => {
  // 计算formatParts中从开始到当前位置的input类型元素数量
  return formatParts.value.slice(0, formatPartsIndex + 1).filter(part => part.type === 'input').length - 1
}

// 处理输入事件
const handleInput = (formatPartsIndex: number) => {
  const inputIndex = getInputIndex(formatPartsIndex)
  const currentInput = inputValues.value[inputIndex]
  const currentPart = formatParts.value[formatPartsIndex]

  // 检查是否达到最大长度
  if (
    currentPart &&
    currentPart.type === 'input' &&
    currentInput &&
    currentInput.length === currentPart.length
  ) {
    // 找到下一个输入框
    const nextInputPartsIndex = formatParts.value.findIndex(
      (part, i) =>
        i > formatPartsIndex &&
        part.type === 'input',
    )

    if (nextInputPartsIndex !== -1) {
      // 计算对应的inputValues索引
      const nextInputIndex = getInputIndex(nextInputPartsIndex)
      
      // 自动聚焦到下一个输入框
      setTimeout(() => {
        const inputs = document.querySelectorAll('.part-input')
        if (inputs[nextInputIndex]) {
          ;(inputs[nextInputIndex] as HTMLInputElement).focus()
        }
      }, 100)
    }
  }

  updateModelValue()
}

// 监听外部modelValue变化 - 仅在初始化时解析一次，避免用户输入时的循环更新
parseValueToInputs(props.modelValue)

watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && !isTemplateSelected.value) {
      // 只在未选择模板时解析传入的值
      parseValueToInputs(newVal)
    }
  }
)

// 监听外部loading状态变化
watch(
  () => props.loading,
  (newVal) => {
    isLoading.value = newVal
  },
)

// 初始化
// 不自动选择第一个模板
isTemplateSelected.value = false
</script>

<style lang="scss" scoped>
.c-property-certificate-input-wrapper {
  position: relative;
  display: inline-block;
  width: 100%;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.input-wrapper {
  display: flex;
  align-items: center;
  flex: 1;
  padding: 8px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  transition: border-color 0.3s;
  position: relative;

  &:hover {
    border-color: #c0c4cc;
  }

  &.is-disabled {
    background-color: #f5f7fa;
    cursor: not-allowed;
  }
}

.format-part {
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: 14px;
  color: #606266;
}

.part-input {
  padding: 0 5px;
  border: none;
  outline: none;
  font-size: 14px;
  color: #303133;
  background: transparent;
  border-bottom: 1px solid #dcdfe6;
  text-align: center;
  box-sizing: border-box;

  &::placeholder {
    color: #c0c4cc;
    font-size: 12px;
  }

  &:focus {
    border-bottom-color: #409eff;
  }

  &:disabled {
    background-color: transparent;
    cursor: not-allowed;
    opacity: 0.6;
  }
}

.required-mark {
  position: absolute;
  right: -12px;
  top: 50%;
  transform: translateY(-50%);
  color: #f56c6c;
  font-size: 14px;
}

.clear-icon {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #c0c4cc;
  cursor: pointer;
  transition: color 0.3s;
  font-size: 16px;
  z-index: 10;

  &:hover {
    color: #909399;
  }
}
</style>
